package com.baic.ibase.interceptor;

import com.baic.ibase.utils.token.TokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor, ApplicationContextAware {

    private ApplicationContext applicationContext = null;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Token");
        if (token == null || token.isEmpty()) {
            response.setStatus(401);
            return false;
        }
        if (!TokenUtils.verify( token)) {
            response.setStatus(401);
            return false;
        }

        String userId = TokenUtils.getUserId(token);
        request.setAttribute("userId", userId);
        request.setAttribute("userName", TokenUtils.getUserName(token));
        log.info("用户ID: {}, 用户名: {}", userId, TokenUtils.getUserName(token));
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
